package freespiritsocial.io.user.ui.adapter

import androidx.core.view.isVisible
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.sendbird.android.GroupChannel
import freespiritsocial.io.user.R
import freespiritsocial.io.user.data.model.bean.getFreeSpiritTime
import freespiritsocial.io.user.databinding.ItemMessageBinding
import freespiritsocial.io.user.ext.circleImageUrl
import freespiritsocial.io.user.ext.setAdapterAnimation
import freespiritsocial.io.user.util.CacheUtil
import java.util.*

/**
 * 消息适配器
 */
class MessageAdapter(
    data: ArrayList<GroupChannel> = arrayListOf(),
    layoutResIdRes: Int = R.layout.item_message
):
    BaseQuickAdapter<GroupChannel,BaseDataBindingHolder<ItemMessageBinding>>(layoutResIdRes,data) {

    init {
        setAdapterAnimation(0)
    }

    private val userInfo by lazy(LazyThreadSafetyMode.NONE) {
        CacheUtil.getUser()
    }


    override fun convert(holder: BaseDataBindingHolder<ItemMessageBinding>,item: GroupChannel) = with(holder.dataBinding) {
        val member = item.members.find { it.userId != userInfo?.resourceId }
        if (member != null) {
            this?.tvMessage?.text = item.lastMessage.message
            this?.tvName?.text = member.nickname
            this?.ivAvatar?.circleImageUrl(member.profileUrl)
//            this?.smallAvatar?.circleImageUrl(member.profileUrl)
            this?.tvCount?.isVisible = item.unreadMessageCount > 0
            this?.tvCount?.text = item.unreadMessageCount.toString()
            val offsetTime = (System.currentTimeMillis() - item.lastMessage.createdAt).div(1000L)
            this?.tvDate?.text = offsetTime.getFreeSpiritTime(item.lastMessage.createdAt)
        } else {
            this?.tvMessage?.text = item.lastMessage.message
            this?.tvName?.text = "Account has been cancelled"
            this?.ivAvatar?.circleImageUrl("")
            val offsetTime = (System.currentTimeMillis() - item.lastMessage.createdAt).div(1000L)
            this?.tvDate?.text = offsetTime.getFreeSpiritTime(item.lastMessage.createdAt)
        }
    }
}